package com.sherllinhe.member.service;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.date.DateTime;
import cn.hutool.core.util.ObjUtil;
import cn.hutool.core.util.StrUtil;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.sherllinhe.common.resp.PageResp;
import com.sherllinhe.common.util.SnowUtil;
import com.sherllinhe.member.domain.Ticket;
import com.sherllinhe.member.domain.TicketExample;
import com.sherllinhe.member.mapper.TicketMapper;
import com.sherllinhe.member.req.TicketQueryReq;
import com.sherllinhe.member.resp.TicketQueryResp;
import io.seata.core.context.RootContext;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.sherllinhe.common.req.MemberTicketReq;

import java.util.List;

/**
 * 功能：
 * 作者：Sherllin He
 * 日期：
 */
@Slf4j
@Service
public class TicketService {
    @Autowired
    private TicketMapper ticketMapper;
    // 新增和编辑车票
    public void save(MemberTicketReq req) throws Exception {
        log.info("seata全局事务的ID：{}", RootContext.getXID());
        DateTime now = DateTime.now();
        Ticket ticket = BeanUtil.copyProperties(req, Ticket.class);
        ticket.setId(SnowUtil.getSnowflakeNextId());
        ticket.setCreateTime(now);
        ticket.setUpdateTime(now);
        ticketMapper.insert(ticket);
        //模拟被调用方出现异常
//        if(1==1){
//            throw new Exception("测试事务异常");
//        }

    }
    // 分页查询车票列表
    public PageResp<TicketQueryResp> queryList(TicketQueryReq req){
        TicketExample example = new TicketExample();
        example.setOrderByClause("update_time desc");
        TicketExample.Criteria criteria = example.createCriteria();
        //if(ObjUtil.isNotNull(req.getMemberId())){
            //criteria.andMemberIdEqualTo(req.getMemberId());
        //}
        if(ObjUtil.isNotNull(req.getMemberId())){
            criteria.andMemberIdEqualTo(req.getMemberId());
        }
        log.info("查询页码:{}",req.getPage());
        log.info("每页条数:{}",req.getSize());
        PageHelper.startPage(req.getPage(),req.getSize());
        List<Ticket> ticketList = ticketMapper.selectByExample(example);

        PageInfo<Ticket> pageInfo = new PageInfo<>(ticketList);
        log.info("总条数:{}", pageInfo.getTotal());
        log.info("总页数:{}", pageInfo.getPages());

        List<TicketQueryResp> list = BeanUtil.copyToList(ticketList, TicketQueryResp.class);

        PageResp<TicketQueryResp> pageResp = new PageResp<>();
        pageResp.setList(list);
        pageResp.setTotal(pageInfo.getTotal());

        return pageResp;
    }
    //删除车票
    public void delete(Long id){
        ticketMapper.deleteByPrimaryKey(id);
    }
}
